<template>
    <div class="upload_cropper_container" :style="{ '--width': width, '--height': height }">
        <el-upload action="#"
            :class="{single_file}"
            list-type="picture-card"
            :auto-upload="false"
            :accept="uploadOptions.accept"
            :limit="uploadOptions.limit"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-change="changeUpload"
            :on-exceed="exceedUpload"
        >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="isEditFlag" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                </span>
            </div>
            <template v-if="$utils.isNotEmpty(uploadOptions.tip)">
                <div slot="tip" class="el-upload__tip" v-html="uploadOptions.tip" />
            </template>
        </el-upload>
    </div>
</template>

<script>

export default {
    name: "UploadPic",
    props: {
        options: {
            type: Object,
            default() {
                return {};
            },
        },
        data: {
            type: Array,
            default() {
                return [];
            },
        },
        width: {
            type: String,
            default: '200px',
        },
        height: {
            type: String,
            default: '200px',
        },
        isEditFlag:  {
            type: Boolean,
            default() {
                return true;
            }
        },
    },
    updated() {

    },
    beforeDestroy() {
        let _this = this;
        _this.fileList = [];
        _this.returnResList = [];
    },
    computed: {
        single_file() {
            let fileList = this.fileList;
            return (this.$utils.isNotEmptyList(fileList) && this.uploadOptions.limit === fileList.length) || !this.isEditFlag;
        },
    },
    watch: {
        options: {
            handler() {
                this.initOptions(this.options);
            },
            deep: true,
            immediate: true,
        },
        data: {
            handler() {
                this.initData(this.data);
            },
            deep: true,
            immediate: true,
        },
    },
    data() {
        return {
            fileList: [],
            uploadOptions: {
                fileName: "",
                accept: 'image/*',
                limit: 1,
            },
            scale: 1,
            trueHeight: 0,
            trueWidth: 0,
            returnResList: [],
        }
    },
    methods: {
        initOptions(options) {
            let _this = this;
            _this.uploadOptions = $.extend({},_this.uploadOptions, options);
        },
        initData(data) {
            let _this = this;
            _this.fileList = [];
            _this.returnResList = [];
            if (data && data.length > 0) {
                data.forEach(async (item, index) => {
                    await _this.getFileInfoWithUrl(item.file_sid).then(fileInfo => {
                        _this.returnResList.push(fileInfo);
                        _this.fileList.push({
                            sid: fileInfo.sid,
                            name: fileInfo.original_file_name,
                            url: fileInfo.url,
                        });
                    });
                });
            }
        },
        // 文件状态改变时
        changeUpload(file, fileList) {
            let _this = this;
            if (file && file.name) {
                let picSuffix = file.name.substring(file.name.lastIndexOf("."));
                if (!_this.uploadOptions.accept) {
                    return;
                }
                // 在插件上展示图片
                let reader = new FileReader();
                reader.readAsDataURL(file.raw);
                reader.onload = () => {
                    // console.log("file 转 base64结果：" + reader.result);
                    const loading = this.$loading({
                        lock: true,
                        text: '正在生成裁剪图片........................',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    let result = reader.result;
                    _this.uploadFile(result, loading);
                }
            }
        },
        // 文件超出个数限制时的钩子
        exceedUpload(files, fileList){
            this.$message.error(`最多只能上传${this.uploadOptions.limit}张图片！`);
        },
        // 上传文件之前
        beforeUpload() {

        },
        // 裁剪关闭
        handleClose() {
            let _this = this;
            _this.fileList = [];
            _this.returnResList = [];
        },
        // 上传文件
        uploadFile(data, loading) {
            let _this = this;
            _this.storeDispatch('uploadBase64', {
                base64: data,
                associate_biz_table: _this.uploadOptions.associate_biz_table,
                associate_biz_sid: undefined,
                associate_biz_field_tag: _this.uploadOptions.associate_biz_field_tag,
            }).then(result => {
                let resData = result.data || {};
                let url = _this.getFileWithType(resData.sid, resData.file_type);
                let obj = {
                    sid: resData.sid,
                    name: resData.original_file_name,
                    url,
                };
                loading.close();
                _this.fileList.push(obj);
                _this.returnResList.push(resData);
                _this.$emit("success", _this.returnResList);
            }).catch(() => {
                loading.close();
                _this.$message.error("上传失败");
            });
        },
        // 移除
        handleRemove(file) {
            let _this = this;
            for(let i = 0; i < _this.fileList.length; i++) {
                if (file && file.uid && _this.fileList[i].uid === file.uid) {
                    _this.fileList.splice(i, 1);
                    _this.returnResList.splice(i, 1);
                }
            }
            _this.$emit("success", _this.returnResList);
        },
        // 查看
        handlePictureCardPreview(file) {
            window.open(file.url, '_blank')
        },
        // 下载
        handleDownload(file) {
            this.download(file.url, file.name);
        },
        download (src, fileName) {
            let x = new XMLHttpRequest();
            x.open("GET", src, true);
            x.responseType = 'blob';
            x.onload = function(e) {
                let url = window.URL.createObjectURL(x.response)
                let a = document.createElement('a');
                a.href = url
                a.download = fileName
                a.click()
            }
            x.send();
        },
    }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
/deep/ .el-upload--text {
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: var(--width);
    height: var(--height);
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    display: flex;
    align-items: center;
    justify-content: center;
}
.single_file {
    /deep/ .el-upload--picture-card {
        display: none;
    }

    /deep/ .el-upload-list--picture-card {
        .el-upload-list__item {
            margin: 0;
        }
    }
}
</style>
